import { PlaceUseLog } from './../../models/plactType';
import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { UseAxisFragment } from './place-use-axis.component';
import * as dayjs from 'dayjs';
import * as Enumerable from 'linq';

@Injectable({
  providedIn: 'root'
})
export class PlaceUseAxisService {
  setDataValue$: Subject<{
    fragmentList: UseAxisFragment[];
    begin: number;
    end: number;
  }> = new Subject();

  selectedFreeFragment$: Subject<UseAxisFragment> = new Subject();

  sliceTheTime(usgLogs: PlaceUseLog[], begin: number, end: number): UseAxisFragment[] {
    let fragmentList: UseAxisFragment[] = [];
    for (const item of usgLogs) {
      let fragment = new UseAxisFragment(
        item.beginTime,
        item.endTime,
        'using'
      );
      fragment.data = item;
      fragmentList.push(fragment);
    }

    if (fragmentList.length == 0) {
      let headItem = new UseAxisFragment(
        begin, end, 'free'
      );
      fragmentList.push(headItem);
    }
    else {
      fragmentList = Enumerable.from(fragmentList).orderBy(x => x.fromTime).toArray();
      let tmpFragmentList = [...fragmentList];

      let fTime = begin;
      let count = 0;
      let isBreak: boolean = false;

      while (!isBreak) {
        try {
          console.log('sliceTheTime', dayjs(fTime).format('YYYY-MM-DD HH:mm'))
          let fragementItem = tmpFragmentList.find(x => x.fromTime == fTime);
          if (fragementItem) {
            fTime = fragementItem.toTime;
            if (fTime == end) {
              isBreak = true;
            }
          }
          else {
            let nodeEndTime: number;
            if (count > tmpFragmentList.length - 1) {
              nodeEndTime = end;
              isBreak = true;
            }
            else {
              nodeEndTime = tmpFragmentList[count].fromTime;
            }

            if (fTime > nodeEndTime) {
              nodeEndTime = tmpFragmentList[count].toTime;
              tmpFragmentList[count].status = 'using';
            }
            else {
              fragementItem = new UseAxisFragment(fTime, nodeEndTime, 'free');
              fragmentList.push(fragementItem);
            }

            fTime = nodeEndTime;
            count++;
          }
        } catch (error) {
          console.log(error);
          isBreak = true;
        }

      }

    }

    // console.log(fragmentList);
    // fragmentList.forEach(item => {
    //   console.log('UseAxisFragment 11111', dayjs(item.fromTime).format('YYYY-MM-DD HH:mm'), dayjs(item.toTime).format('YYYY-MM-DD HH:mm'), item.status);
    // })


    return fragmentList;
  }

  checkTimeCanUse(){
    
  }
}
